<template>
  <el-dialog
    title="更新数据"
    width="30%"
    :append-to-body="true"
    :visible.sync="showTag"
  >
    <span>正在更新{{ form.name }}</span>
  </el-dialog>
</template>

<script>
export default {
  name: "CoclassUpdateDialog",
  data() {
    return {
      form: {},
      showTag: false
    };
  },
  methods: {
    show() {
      this.showTag = true;
      this.doUpdate(1);
    },
    hide() {
      this.showTag = false;
    },
    async doUpdate(pageNum) {
      const data = await this.$coclassService.list({ pageSize: 1, pageNum });
      if (data && data.data && data.data.length) {
        this.form = data.data[0];
        // 更新是否有子节点
        await this.updateChildren();
        const isValid = await this.isValidNode(this.form.id);
        if (!isValid) {
          await this.deleteNode(this.form.id);
          pageNum--;
        }
        await this.doUpdate(++pageNum);
      } else {
        this.$emit("ok");
        this.hide();
      }
    },

    /**
     * 更新是否有子节点
     * @returns {Promise<void>}
     */
    async updateChildren() {
      const { form } = this;
      const { count } = await this.$coclassService.list({
        fid: form.id,
        pageSize: 1
      });
      await this.$coclassService.update({
        id: form.id,
        has_children: count
      });
    },

    /**
     * 是否有效节点
     * @param id
     * @returns {Promise<boolean|*>}
     */
    async isValidNode(id) {
      const node = await this.$coclassService.detail(id);
      if (node && node.hasOwnProperty("fid")) {
        if (node.fid === 0 || node.fid === "0") return true;
        // eslint-disable-next-line no-return-await
        else return await this.isValidNode(node.fid);
      } else return false;
    },

    async deleteNode(id) {
      await this.$coclassService.del(id);
    }
  }
};
</script>

<style scoped></style>
